package org.jcms.web.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jcms.model.Book;
import org.jcms.model.Customer;
import org.jcms.service.BookServiceI;
import org.jcms.uitils.CookieUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


/**
 * 显示购物车中的物品
 * @author Administrator
 *
 */
public class CustomerShowCart extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	public CustomerShowCart() {
		super();
	}

	public void destroy() {
		super.destroy(); 
	}


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ApplicationContext ac = WebApplicationContextUtils
				.getRequiredWebApplicationContext(this.getServletContext());
		BookServiceI bookServiceI = (BookServiceI) ac
				.getBean("bookServiceImpl");
		Customer customer = (Customer) request.getSession().getAttribute("customer");
		String cookieName = "bookTrolley";
		String cookiePath = request.getContextPath() + "/customer";
		String retJson = "";

		JSONObject jsonObject = new JSONObject();

		try {
		if(customer==null){
			jsonObject.put("total", 0);
		}else{
			 cookieName = "bookTrolley"+customer.getCustomerId();
			 JSONArray jsonArray = CookieUtil.gets(cookieName, cookiePath, 30*24*3600, request, response);
				List<HashMap<String, String>> bookls = new ArrayList<HashMap<String, String>>();
				if(jsonArray==null){
					jsonObject.put("total", 0);
				}else{
					jsonObject.put("total", jsonArray.length());
					for(int i=0;i<jsonArray.length();i++){
						HashMap<String, String> tempMap = new HashMap<String, String>();
						Book book = bookServiceI.findById(jsonArray.getJSONObject(i).getString("bookIsbn"));
						if(book!=null){
							tempMap.put("bookIsbn",book.getBookIsbn());
							tempMap.put("bookName",book.getBookName());
							tempMap.put("bookOrderNumber",jsonArray.getJSONObject(i).getString("orderBookNumber"));
							bookls.add(tempMap);
						}
					}
				}
				jsonObject.put("rows", bookls);
				retJson = jsonObject.toString();
		}
			
		}

		catch (Exception e) {

		}

		finally {
			response.getOutputStream().write(retJson.getBytes("utf-8"));
		}
	}

	public void init() throws ServletException {
	
	}

}
